﻿using Commons.Commands;
using Commons.Commands.Results;
using Commons.Injector;
using System;

namespace Commons.Services.Commands
{
    public class CommandService
    {

        public OperationResult CreateUserAccountCommand(string userName, string password)
        {
            CreateUserAccountCommand cmd = NewCommand<CreateUserAccountCommand>("createUserAccountCommand");
            cmd.UserName = userName;
            cmd.Password = password;

            return Execute(cmd);
        }

        public OperationResult GetUserAccountsCommand()
        {
            GetUserAccountsCommand cmd = NewCommand<GetUserAccountsCommand>("getUserAccountsCommand");
            return Execute(cmd);
        }
        
        private T NewCommand<T>(string refId) where T : ICommand
        {
            return Context.Instance.GetObject<T>(refId);
        }

        private OperationResult Execute(ICommand command)
        {
            try
            {
                Debug.LogFormat("Try to run command {0}", command.ToString());
                
                OperationResult result = command.Execute();

                if (result.Success)
                    Debug.LogFormat("Finish command {0}", command.ToString());
                else
                    Debug.LogFormat("Finish with errors command {0}", command.ToString());
            
                return result;
            }
            catch (Exception e)
            {
                Debug.LogException(e);

                return new OperationResult(e.Message);
            }
        }

    }
}
